<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Connect MetaMask</title>
</head>
<body>

  <h1>MetaMask 连接示例</h1>
  <button id="connectButton">连接钱包</button>
  <p id="status">未连接</p>

  <!-- 引入 ethers.js（轻量且易用） -->
  <script src="js/ethers.umd.min.js"></script>

  <script>
    // 检查是否安装了 MetaMask
    if (typeof window.ethereum === 'undefined') {
      document.getElementById('status').textContent = '请安装 MetaMask';
    }

    const connectButton = document.getElementById('connectButton');
    const status = document.getElementById('status');

    // 连接钱包
    connectButton.onclick = async () => {
      try {
        const provider = new ethers.providers.Web3Provider(window.ethereum)

        // MetaMask requires requesting permission to connect users accounts
        await provider.send("eth_requestAccounts", []);

        // The MetaMask plugin also allows signing transactions to
        // send ether and pay to change state within the blockchain.
        // For this, you need the account signer...
        const signer = provider.getSigner()

        const address = await signer.getAddress()
        status.textContent = `已连接: ${address}`;
      } catch (err) {
        if (err.code === 4001) {
          status.textContent = '用户拒绝连接';
        } else {
          status.textContent = '连接失败';
          console.error(err);
        }
      }
    };
  </script>

</body>
</html>